import { createPinia, defineStore, storeToRefs } from 'pinia'

const pinia = createPinia()

// 公共store
const useStore = defineStore('index', {
  state: () => ({
    // 主题
    theme: localStorage.getItem('theme') || 'light', // light/dark

    // 路由
    routers: [],

    // map配置
    mapConfig: {
      id: 'map',
    },
  }),

  getters: {},

  actions: {
    // 设置 State
    setState({ key, value }: { key: S; value: any }) {
      this[key] = value
    },
  },
})

// 初始化
function init() {
  // 遍历文件导入
  const modulesFiles = (import.meta as any).globEager('./**/*.ts')
  let modules = useStore()

  Object.keys(modulesFiles).forEach((fileName) => {
    const name = fileName.replace(/\.\/|\.ts/g, '')
    const nameList = name.split('/')
    let nameModule =
      nameList[nameList.length - 1] == 'index'
        ? nameList[nameList.length - 2]
        : nameList[nameList.length - 1]

    modulesSet({
      modules,
      module: modulesFiles[fileName].useStore(nameModule),
      nameList,
    })
  })

  window.$store = modules
  window.$storeToRefs = storeToRefs
}
function modulesSet({
  modules,
  module,
  modulesPrev,
  nameList,
  i = 0,
}: {
  modules: any
  module: any
  nameList: any
  modulesPrev?: any
  i?: any
}) {
  let name = nameList[i]

  if (nameList.length == i + 1) {
    if (name == 'index') {
      modulesPrev[nameList[i - 1]] = Object.assign(
        module,
        modulesPrev[nameList[i - 1]],
      )
      return
    }

    modules[name] = module
    return
  }

  modules[name] = modules[name] || {}

  modulesSet({
    modules: modules[name],
    modulesPrev: modules,
    nameList,
    module,
    i: ++i,
  })
}

export default (app: any) => {
  app.use(pinia)
  init()
}
